<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Model\QmGameAccount;
use Exception;
use TencentCloud\Common\Credential;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Sms\V20210111\SmsClient;

class SmsService {

    /**
     * 短信发送申请试用账号的信息给管理员
     */
    public function sendSms($mobile, $type = 1): array {
        $code = $this->randNumber(0, 999999);
        $cred = new Credential(config('qcloud.secretId'), config('qcloud.secretKey'));
        $client = new SmsClient($cred, "ap-guangzhou");

        $temId = '';
        switch ($type) {
            case 1://登录
                $temId = '1840546';
                break;
            case 2://绑定
                $temId = '1840547';
                break;
            case 3://重置密码
                $temId = '1920418';
                break;
//            case 4://修改密码
//                $temId = '1920421';
//                break;
        }

        $req = new SendSmsRequest();
        $req->SmsSdkAppId = '1400599197';
        $req->SignName = '暗夜办公室公众号';
        $req->PhoneNumberSet = ['+86' . $mobile];
        $req->TemplateId = $temId;
        $req->TemplateParamSet = [$code];

        $resp = $client->SendSms($req);

        $result = json_decode($resp->toJsonString(), true);

        return ['code' => $result['SendStatusSet'][0]['Code'], 'data' => $code];
    }

    /**
     * 获取一定范围内的随机数字 位数不足补零
     * @param integer $min 最小值
     * @param integer $max 最大值
     * @return string
     * @throws Exception
     */
    public static function randNumber(int $min, int $max): string {
        return sprintf("%0" . strlen((string)$max) . "d", (string)random_int($min, $max));
    }

    /**
     * 检查手机号绑定状态
     * @param $mobile
     * @param $platform
     * @return void
     * @throws Exception
     */
    public function checkAccount($mobile, $platform): void {
        $info = QmGameAccount::query()->where('mobile', $mobile)
            ->where('platform', $platform)
            ->where('status', 1)
            ->first();
        if (!empty($info)) {
            throw new Exception('该手机号已经绑定', ErrorCode::RECORD_NOT_FOUND);
        }
    }
}